<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form class="permission-form" :form="form">
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="唯一标识" v-show="xsFlag">
        <a-input v-decorator="['id']" :disabled="true" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户名" hasFeedback>
        <a-input
          placeholder="起一个名字"
          autocomplete="name"
          v-decorator="['name', { rules: [{ required: true, message: '用户名不能为空' }] }]"
        />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="区域" hasFeedback>
        <area-select @change="selectArea" :default-value="defaultArea"></area-select>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="详细地址" hasFeedback>
        <a-textarea
          placeholder="请输入详细地址"
          autocomplete="detailed"
          v-decorator="['detailed', { rules: [{ required: true, message: '详细地址不能为空' }] }]"
        />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户名id" hasFeedback>
        <a-input
          placeholder="请输入用户id"
          autocomplete="userId"
          v-decorator="['userId', { rules: [{ required: true, message: '用户名不能为空' }] }]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="头像头" hasFeedback>
        <a-input
          placeholder="请输入head"
          autocomplete="head"
          v-decorator="['head', { rules: [{ required: true, message: '头像头不能为空' }] }]"
        />
      </a-form-item>

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" v-show="!xsFlag" hasFeedback> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" hasFeedback>
        <a-input-password
          placeholder="密码"
          autocomplete="current-password"
          v-decorator="['password', { rules: [{ required: true, message: '密码不能为空' }] }]"
        />
      </a-form-item> -->

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="性别" hasFeedback validateStatus="success">
        <a-select v-decorator="['sex', { initialValue: 0 }]">
          <a-select-option :value="0">男</a-select-option>
          <a-select-option :value="1">女</a-select-option>
          <a-select-option :value="2">未知</a-select-option>
        </a-select>
      </a-form-item> -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否默认" hasFeedback>
        <a-select v-decorator="['isDefault', { initialValue: 0 }]">
          <a-select-option :value="0">是</a-select-option>
          <a-select-option :value="1">否</a-select-option>
        </a-select>
      </a-form-item>

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="邮箱" hasFeedback>
        <a-input
          :rows="5"
          placeholder="请输入邮箱"
          v-decorator="[
            'email',
            {
              rules: [
                { required: true, message: '邮箱不能为空' },
                { type: 'email', message: '请输入正确的邮箱格式' }
              ]
            }
          ]"
        />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="github账号" hasFeedback>
        <a-input :rows="5" placeholder="请输入github账号名字" v-decorator="['githubLogin']" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="gitee账号" hasFeedback>
        <a-input :rows="5" placeholder="请输入gitee账号名字" v-decorator="['giteeLogin']" />
      </a-form-item> -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="电话" hasFeedback>
        <a-input
          :rows="5"
          placeholder="请输入电话"
          v-decorator="[
            'tel',
            {
              rules: [
                { required: true, message: '电话不能为空' },
                { pattern: new RegExp(/^1[3-9]\d{9}$/), message: '电话格式不对' }
              ]
            }
          ]"
        />
      </a-form-item>
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="头像" hasFeedback>
        <a-upload
          :customRequest="uploadimage"
          list-type="picture-card"
          :file-list="fileList"
          @preview="handlePreview"
          @change="handleChange"
          :remove="removeFile"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleC">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item> -->
      <!-- <a-divider>拥有角色</a-divider>

      <a-form-item label="角色" name="actions" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
        <a-select
          style="width: 100%"
          mode="multiple"
          :token-separators="[',']"
          v-decorator="['roles', { rules: [{ required: true, message: '角色不能为空' }] }]"
          :allowClear="true"
        >
          <a-select-option v-for="(action, index) in RolesLists" :key="index" :value="action.value">
            {{ action.label }}
          </a-select-option>
        </a-select>
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script>
// import { decryptStr } from '@/utils/passwordUtils'
import areaSelect from '../components/areaSelect.vue'
import areaData from '../modules/areCity.json'
// import { getPermissions } from '@/api/manage'
// import pick from 'lodash.pick'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'RoleModal',
  components: {
    areaSelect
  },
  data() {
    return {
      areaData,
      RolesLists: [],
      defaultArea: ['32', '3205', '320571'],
      xsFlag: false,
      title: '新增角色',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      // mdl: {
      //   actions: [] // 初始化为默认选中的值
      // },

      form: this.$form.createForm(this),
      permissions: [],
      previewVisible: false,
      previewImage: '',
      fileList: [
        /* {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-2',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-3',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-4',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-5',
          name: 'image.png',
          status: 'error'
        } */
      ],
      selectedArea: [],
      region: {
        label: '',
        value: [],
        cityCode: ''
      }
    }
  },
  created() {
    this.loadPermissions()
  },
  mounted() {
    // console.log('mounted', this.areaCity)
  },

  methods: {
    // 选择好之后的回调
    findIndexes(data, targetCodes, currentIndex = [], allPaths = []) {
      // 如果目标 code 数组已经为空，说明已找到所有目标
      if (targetCodes.length === 0) {
        allPaths.push(currentIndex) // 将路径添加到 allPaths 中
        return
      }

      for (let i = 0; i < data.length; i++) {
        const item = data[i]

        // 如果当前 item 的 code 与目标数组的第一个 code 匹配
        if (item.code === targetCodes[0]) {
          // 将当前索引添加到路径中
          const newIndex = [...currentIndex, i]

          // 移除已匹配的 code，并递归检查子节点
          targetCodes.shift()

          // 如果 targetCodes 已空，说明所有目标已找到，返回当前路径
          if (targetCodes.length === 0) {
            allPaths.push(newIndex) // 将路径添加到 allPaths 中
          }

          // 如果存在子节点，继续递归
          if (item.children) {
            this.findIndexes(item.children, targetCodes, newIndex, allPaths)
          }
        }
      }

      return allPaths // 返回所有路径
    },
    selectArea(selectedArea) {
      // this.selectedArea = selectedArea
      console.log('尕布', selectedArea)

      const akk = []
      selectedArea.map((item) => {
        akk.push(item.code)
      })
      console.log('akk', akk)

      const index = this.findIndexes(this.areaData, akk)

      console.log(index[0])
      console.log('选择的地址', selectedArea)
      const aa = selectedArea[0].label + '-' + selectedArea[1].label + '-' + selectedArea[2].label
      this.region = {
        label: aa,
        value: index[0],
        cityCode: selectedArea[2].code
      }
    },
    removeFile(e) {
      console.log('删除文件', e.name)
      // this.$http.post('/common/del', { filename: e.name }).then((res) => {
      //   console.log(res)
      // })
      this.fileList = []
    },
    uploadimage(file, fileList) {
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file) // 'file' 是文件的表单字段名，file 是文件对象
      this.$http
        .post('/common/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 确保请求头设置为 multipart/form-data
          }
        })
        .then((res) => {
          console.log('上传成功', res)
          this.fileList = res.result
        })
      console.log(this.fileList)
    },
    handleC() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    filterByValue(arr, valueArray) {
      return arr.filter((item) => valueArray.includes(item.value))
    },
    // 验证状态的动态显示
    validateStatus(fieldName) {
      const { getFieldError, isFieldTouched } = this.form
      if (isFieldTouched(fieldName) && getFieldError(fieldName)) {
        return 'error'
      }
      return 'success'
    },
    add() {
      console.log('add')
      this.region = {
        label: '',
        value: [],
        cityCode: ''
      }
      this.visible = true
      this.xsFlag = false
      this.title = '新增角色'
      this.defaultArea = []
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue({
            id: '',
            name: '',
            tel: '',
            detailed: '',
            userId: '',
            isDefault: 1,
            head: ''
          })
        })
      })

      this.loadPermissions()
    },
    watch(record) {
      console.log('watch', record)
      this.title = '查看角色'
    },
    returnvalue(arr) {
      return arr.map((item) => {
        return item.value
      })
    },
    getCodesFromIndexPath(data, indexPath) {
      let currentData = data
      const result = []

      for (let i = 0; i < indexPath.length; i++) {
        const index = indexPath[i]
        currentData = currentData[index] // 根据索引获取当前层的数据
        result.push(currentData.code) // 保存当前层的 code
        if (currentData.children) {
          currentData = currentData.children // 进入下一层
        }
      }

      return result
    },
    edit(record) {
      this.mdl = Object.assign({}, record)
      this.visible = true
      console.log('数据', this.mdl)
      this.title = '编辑地址'
      this.xsFlag = true

      // if (record.avatar) {
      //   this.fileList = []
      //   this.fileList.push(JSON.parse(record.avatar))
      // } else {
      //   this.fileList = []
      // }
      this.$nextTick(() => {
        console.log('地址数据', this.getCodesFromIndexPath(this.areaData, this.mdl.region.value))

        this.defaultArea = this.getCodesFromIndexPath(this.areaData, this.mdl.region.value)
        // this.form.setFieldsValue(pick(this.mdl, 'id
        // ', 'name', 'code', 'status'))
        this.form.setFieldsValue({
          // id: this.mdl.id,
          // code: this.mdl.name,
          // status: this.mdl.status,
          // name: this.mdl.code,
          id: this.mdl.id,
          name: this.mdl.name,
          tel: this.mdl.tel,
          detailed: this.mdl.detailed,
          userId: this.mdl.userId,
          head: this.mdl.head,
          isDefault: this.mdl.isDefault === 'true' ? 0 : 1
        })
      })
      // console.log('this.mdl', this.mdl)
    },
    close() {
      // this.$emit('close')

      this.visible = false
    },
    handleOk() {
      // // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          // console.log('form values', values)
          // const aa = this.filterByValue(this.RolesLists, values.roles)
          // console.log('j橘角色', aa)
          if (values.id > 0) {
            const tabledate = this.$removeSpacesFromObject(values)
            // console.log('修改头像', this.fileList)
            // console.log('用户的相关信息', tabledate)
            const data = {
              ...tabledate,
              region: this.region,
              isDefault: tabledate.isDefault === 0 ? 'true' : 'false'
            }
            console.log('shuju', data)

            this.$http.put('/userAddress/update', data).then((res) => {
              console.log('res', res)
              if (res.code === 200) {
                this.$message.success('修改成功')
                this.$emit('ok')
              }
            })
          } else {
            const tabledate = this.$removeSpacesFromObject(values)

            // console.log('表格数据', tabledate)
            const data = {
              ...tabledate,
              region: this.region,
              isDefault: tabledate.isDefault === 0 ? 'true' : 'false'
            }
            // console.log('sui', data)

            this.$http.post('/userAddress/insert', data).then((res) => {
              console.log('res', res)
              if (res.code === 200) {
                this.$message.success('添加成功')
                this.$emit('ok')
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChangeCheck(permission) {
      permission.indeterminate =
        !!permission.selected.length && permission.selected.length < permission.actionsOptions.length
      permission.checkedAll = permission.selected.length === permission.actionsOptions.length
    },
    onChangeCheckAll(e, permission) {
      Object.assign(permission, {
        selected: e.target.checked ? permission.actionsOptions.map((obj) => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    del(e) {
      console.log('删除', e)
    },
    disable() {},
    loadPermissions() {
      // const that = this
      // console.log(that)
      this.$http
        .get('/sysRole/roleOptions')
        .then((res) => {
          // console.log('下拉权限', res)
          if (res.code === 200) {
            this.RolesLists = res.result
            // console.log('数据', this.RolesLists)
          }
        })
        .catch((err) => {
          console.log('出错', err)
        })
    }
  }
}
</script>

<style scoped></style>
